#!/bin/bash
# SPDX-License-Identifier: LGPL-2.1-or-later
set -e

if [ "$1" = "build" ] || ((NO_BUILD)); then
    exit 0
fi

# shellcheck source=/dev/null
. "$BUILDROOT/usr/lib/os-release"

if [ ! -f "pkg/$ID/PKGBUILD" ]; then
    echo "PKGBUILD not found at pkg/$ID/PKGBUILD, run mkosi once with -ff to make sure the PKGBUILD is cloned" >&2
    exit 1
fi

# We get depends and optdepends from .SRCINFO as getting them from the PKGBUILD is rather complex.
sed --expression 's/^[ \t]*//' "pkg/$ID/.SRCINFO" |
    grep --regexp '^depends =' --regexp '^optdepends =' |
    sed --expression 's/^depends = //' --expression 's/^optdepends = //' --expression 's/:.*//' --expression 's/=.*//' |
    xargs --delimiter '\n' mkosi-install

# We get makedepends from the PKGBUILD as .SRCINFO can't encode conditional dependencies depending on
# whether some environment variable is set or not.
# shellcheck source=/dev/null
_systemd_UPSTREAM=1 . "pkg/$ID/PKGBUILD"

# shellcheck disable=SC2154
mkosi-install "${makedepends[@]}"
